#ifdef GLUT
#include <GL/glut.h>
#endif
#include <pthread.h>
#include <stdio.h>

#include "log.h"

#include "scilp.h"

#define IMAGE_WIDTH  1024
#define IMAGE_HEIGHT 1024

#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 1024

unsigned char *disptr = NULL;

static int wdw;
static unsigned char damaged=1;

extern log_default_streams_t ilpl;

#ifdef GLUT
void ilpDisplayTimer(int dummy)
{
  if (damaged)
  {
    glutPostWindowRedisplay(wdw);
    damaged = 0;
  }
   
  glutTimerFunc(10, ilpDisplayTimer, 0);
}

void ilpDisplayDraw(void)
{
  glDrawPixels(IMAGE_WIDTH, IMAGE_HEIGHT, GL_LUMINANCE, GL_UNSIGNED_BYTE, disptr);
  glutSwapBuffers();
}

void *ilpDisplayThread(void *dummy)
{
  return NULL;

  lprintf(STREAM(ilpl.info), "GLUT thread started");

  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

  /* Init X window */
  glutInitWindowPosition(1400-IMAGE_WIDTH-10, 10);
  glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
  wdw = glutCreateWindow("Output");
  glutDisplayFunc(ilpDisplayDraw);
  glutTimerFunc(100, ilpDisplayTimer, 0);

  /* Init GL window */
  glClearColor(0.0, 0.0, 0.0, 1.0);
  glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glViewport(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
  gluOrtho2D(0,IMAGE_WIDTH, 0, IMAGE_HEIGHT); 
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glScalef(1,1,1); 
  glRasterPos2d(0,IMAGE_HEIGHT-1);
  glPixelZoom(1,-1);

  lprintf(STREAM(ilpl.debug), "Starting GLUT main loop");

  glutMainLoop();  

  return NULL;
}
#endif

void ilpDisplayInit(int argc, char **argv)
{
  pthread_t thread;
  pthread_attr_t attr;

#ifdef GLUT
  lprintf(STREAM(ilpl.notice), "Initializing GLUT display");
#endif

  disptr = (unsigned char*) malloc(IMAGE_WIDTH*IMAGE_HEIGHT);

#ifdef GLUT
  glutInit(&argc, argv);
  
  pthread_attr_init(&attr);
  pthread_create(&thread, &attr, ilpDisplayThread, NULL);
#endif
}

void ilpDisplayDamage(void)
{
  lprintf(STREAM(ilpl.crawl), "Refreshing display");
  damaged = 1;
}
